package cn.globalph.housekeeper.ui.login

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.fragment.findNavController
import cn.globalph.housekeeper.EventObserver
import cn.globalph.housekeeper.R
import cn.globalph.housekeeper.data.retrofit.HttpManager
import cn.globalph.housekeeper.databinding.FragmentLoginBinding
import cn.globalph.housekeeper.ui.BaseFragment
import cn.globalph.housekeeper.ui.main.MainActivity
import kotlinx.android.synthetic.main.fragment_login.*

class LoginFragment :BaseFragment(){
    override var barColor = R.color.white
    private lateinit var binding:FragmentLoginBinding

    @Suppress("UNCHECKED_CAST")
    private val viewModel:LoginViewModel by lazy {
        ViewModelProviders.of(this,object : ViewModelProvider.Factory{
            override fun <T : ViewModel?> create(modelClass: Class<T>): T {
                val repository = LoginRepository(HttpManager.getInstance())
                return LoginViewModel(repository) as T
            }

        }).get(LoginViewModel::class.java)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentLoginBinding.inflate(inflater,container,false)
        binding.viewModel = viewModel
        return binding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        binding.lifecycleOwner = this.viewLifecycleOwner

        bar_back.setOnClickListener {
            findNavController().popBackStack()
        }

        viewModel.toastEvent.observe(this, EventObserver{
            TT(it)
        })

        viewModel.loginStatus.observe(this, Observer {
            if(it) {
                startActivity(Intent(activity, MainActivity::class.java))
                activity?.finish()
            }
        })

        viewModel.loading.observe(this, Observer {
            if(it){
                showLoading()
            }else{
                dismissLoading()
            }
        })
    }
}